package com.junjie.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.junjie.entity.Room;
import com.junjie.entity.User;
import com.junjie.services.RoomService;
import com.junjie.services.UserService;
import com.junjie.utils.CommonParams;
import com.junjie.utils.CommonResult;
import com.junjie.utils.JWTUtils;
import com.junjie.utils.TimeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.junjie.utils.PasswordUtil.*;

//用户登录使用的接口
@Controller
@RequestMapping("/user")
@ResponseBody
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RoomService roomService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public CommonResult<Map> login(@RequestBody JSONObject params) {
        String username = params.getString("username");
        String password = params.getString("password");
        //根据用户名去查询对应信息
        User user = userService.getUserByUsername(username);
        System.out.println(user);
        try {
            String decrypt = decrypt(user.getPassword(), password, user.getSalt());
            System.out.println(decrypt);
        } catch (RuntimeException e) {
            //打印异常信息
            System.out.println(e.getMessage());
            return new CommonResult(CommonParams.FAILURE, "账号或者密码错误！");
        }
        //如果登陆成功的话就生成 token 令牌
        //生成JWT令牌
        Map<String, String> payload = new HashMap<>();
        //往JWT令牌中塞入数据
        //将用户 id 存入 token
        payload.put("room_id", user.getRoomId());
        //在 token 中存入用户名
        payload.put("username", user.getUsername());
        //在 token 中存入角色id
        payload.put("role_id", user.getRuleId().toString());
        //在 token 中存入公寓id
        payload.put("apt_id", user.getApt_id().toString());
        String token = JWTUtils.getToken(payload);
        //返回消息
        Map<String, String> returnMsg = new HashMap<>();
        returnMsg.put("token", token);
        returnMsg.put("username", user.getUsername());
        return new CommonResult<>(CommonParams.SUCCESS, "登陆成功！", returnMsg);
    }

    //根据用户名来查询菜单(注意：这个 username 是从 token 中获取的)
    @RequestMapping(value = "/getMenu", method = RequestMethod.GET)
    public CommonResult getMenuByRuleId(HttpServletRequest request) {
        //从 token 数据中拿出 username
        String username = JWTUtils.getTokenStringValue(request.getHeader("Authorization"), "username");
        //获取菜单数据
        String menu = userService.getMenuByUserName(username);
        return new CommonResult<>(CommonParams.SUCCESS, "菜单信息获取成功！", menu);
    }

    //通用的查询接口
    @RequestMapping(value = "/getUserByEntity", method = RequestMethod.POST)
    public CommonResult getUserByEntity(@RequestBody JSONObject json, HttpServletRequest request) {
        User user = new User();
        //这里要控制对应角色的查询条件
        String token = request.getHeader("Authorization");
        //获取公寓的apt_id
        Integer apt_id = Integer.parseInt(JWTUtils.getTokenStringValue(token, "apt_id"));
        //获取角色id
        int rule_id = Integer.parseInt(JWTUtils.getTokenStringValue(token, "role_id"));
        //获取角色的名字
        String username = JWTUtils.getTokenStringValue(token, "username");

        user.setId(json.getInteger("id"));

        if(rule_id == 3) {
            user.setUsername(username);
        } else {
            user.setUsername(json.getString("username"));
        }
        user.setRealName(json.getString("real_name"));
        user.setSex(json.getInteger("sex"));
        user.setAge(json.getInteger("age"));
        user.setBirth(json.getString("birth"));
        user.setTel(json.getString("tel"));
        user.setIdCard(json.getString("id_card"));
        user.setPosition(json.getString("position"));

        if(rule_id != 1) {
            user.setApt_id(apt_id);
        } else {
            user.setApt_id(json.getInteger("apt_id"));
        }

        user.setAptName(json.getString("apt_name"));
        user.setRoomId(json.getString("room_id"));
        user.setInTime(json.getString("in_time"));
        user.setEmail(json.getString("email"));
        user.setRuleId(json.getInteger("rule_id"));
        user.setStatus(json.getInteger("status"));
        List<User> users = userService.getUsersByEntity(user);
        PageHelper.startPage(json.getInteger("pageNum"), json.getInteger("pageSize"));
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return new CommonResult<>(CommonParams.SUCCESS, "查询成功！", pageInfo);
    }

    //获取管理员信息的接口
    @RequestMapping(value = "/getManagers", method = RequestMethod.GET)
    public CommonResult getManagers(@RequestParam("pageNum") Integer pageNum,
                                    @RequestParam("pageSize") Integer pageSize,
                                    HttpServletRequest request) {
        User user = new User();
        String token = request.getHeader("Authorization");
        //获取角色的名字
        String username = JWTUtils.getTokenStringValue(token, "username");
        //获取角色id
        int rule_id = Integer.parseInt(JWTUtils.getTokenStringValue(token, "role_id"));
        //如果是普通管理员登陆
        if(rule_id == 1) {
            //查询所有的管理员
            user.setRuleId(2);
        }
        if(rule_id == 2) {
            //只会对自己进行查询
            user.setUsername(username);
        //如果是员工进行登陆
        }else if(rule_id == 3) {
            return new CommonResult(400,"员工无法获得管理员信息");
        }
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userService.getUsersByEntity(user);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return new CommonResult<>(CommonParams.SUCCESS, "管理员信息查询成功！", pageInfo);
    }

    //获取员工信息的接口
    @RequestMapping(value = "/getEmployees", method = RequestMethod.GET)
    public CommonResult getEmployees(@RequestParam("pageNum") Integer pageNum,
                                     @RequestParam("pageSize") Integer pageSize,
                                     HttpServletRequest request) {
        User user = new User();
        String token = request.getHeader("Authorization");
        //获取角色的名字
        String username = JWTUtils.getTokenStringValue(token, "username");
        //获取公寓的apt_id
        Integer apt_id = Integer.parseInt(JWTUtils.getTokenStringValue(token, "apt_id"));
        //获取角色id
        int rule_id = Integer.parseInt(JWTUtils.getTokenStringValue(token, "role_id"));
        //如果是超级管理员登陆
        if(rule_id == 1) {
            user.setRuleId(3);
        //如果是普通管理员登陆
        }else if(rule_id == 2) {
            user.setApt_id(apt_id);
            user.setRuleId(3);
        }else if(rule_id == 3) {
            //只会对自己进行查询
            user.setUsername(username);
        }else {
            return new CommonResult(400,"查询错误！");
        }
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userService.getUsersByEntity(user);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return new CommonResult<>(CommonParams.SUCCESS, "员工信息查询成功！", pageInfo);
    }

    //增加用户使用的接口
    @RequestMapping(value = "/insertUser", method = RequestMethod.POST)
    public CommonResult insertUser(@RequestBody JSONObject json) throws Exception {
        //这里要使用加密进行过处理
        User user = new User();
        user.setUsername(json.getString("username"));
        //获取随机盐值
        String salt = getSalt();
        //获取密文
        String password = encrypt(json.getString("username"), json.getString("password"), salt);
        user.setSalt(salt);
        user.setPassword(password);
        user.setRealName(json.getString("real_name"));
        user.setSex(json.getInteger("sex"));
        user.setBirth(json.getString("birth"));
        user.setAge(TimeUtils.getAgeByBirth("yyyy-MM-dd", json.getString( "birth")));
        user.setTel(json.getString("tel"));
        user.setIdCard(json.getString("id_card"));
        user.setPosition(json.getString("position"));
        user.setApt_id(json.getInteger("apt_id"));
        user.setAptName(json.getString("apt_name"));
        user.setRoomId(json.getString("room_id"));
        user.setInTime(json.getString("in_time"));
        user.setEmail(json.getString("email"));
        user.setRuleId(json.getInteger("rule_id"));
        user.setStatus(json.getInteger("status"));

        //----------------------------------
        //这里要判断房间的人数是不是已经满了
        User u = new User();
        u.setAptId(user.getAptId());
        u.setRoomId(user.getRoomId());

        //查出对应公寓的对应房间有多少个人
        int persons = userService.getUsersByEntity(u).size();

        //查出对应公寓的对应房间人数范围
        Room room = new Room(); room.setAptId(user.getAptId()); room.setRId(user.getRoomId());
        //这里只会查出一条信息
        int roomLimit = roomService.selectSearchRoom(room).get(0).getType();

        //判断这个用户是否注册过
        User userByUsername = userService.getUserByUsername(user.getUsername());
        if(userByUsername !=  null) {
            return new CommonResult<>(CommonParams.FAILURE, "注册失败，此用户已经注册过了！", null);
        }
        if(persons > roomLimit) {
            return new CommonResult<>(CommonParams.FAILURE, "注册失败，房间人数已经满了！", null);
        }
        //---------------------------------

        return new CommonResult<>(CommonParams.SUCCESS, "注册成功！", userService.insertUser(user));
    }

    //修改接口，这里在修改密码的时候要经过加密算法处理
    @RequestMapping(value = "/updateUserByEntity", method = RequestMethod.POST)
    public CommonResult updateUserByEntity(@RequestBody JSONObject json) {
        User user = new User();
        user.setId(json.getInteger("id"));
        user.setRealName(json.getString("real_name"));
        user.setSex(json.getInteger("sex"));
        user.setAge(json.getInteger("age"));
        user.setBirth(json.getString("birth"));
        user.setTel(json.getString("tel"));
        user.setIdCard(json.getString("id_card"));
        user.setPosition(json.getString("position"));
        user.setApt_id(json.getInteger("apt_id"));
        user.setAptName(json.getString("apt_name"));
        user.setRoomId(json.getString("room_id"));
        user.setInTime(json.getString("in_time"));
        user.setEmail(json.getString("email"));
        user.setRuleId(json.getInteger("rule_id"));
        user.setStatus(json.getInteger("status"));
        return new CommonResult<>(CommonParams.SUCCESS, "修改成功！", userService.updateUser(user));
    }

    //修改密码的接口
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    public CommonResult changePassword(@RequestBody JSONObject params, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        //获取角色的名字
        String username = JWTUtils.getTokenStringValue(token, "username");
        String password = params.getString("password");//旧密码

        String newPassword = params.getString("password1");//新密码

        User user = userService.getUserByUsername(username);
        try {
            String decrypt = decrypt(user.getPassword(), password, user.getSalt());
            //如果没有出错就可以进行修改密码的操作
            if(decrypt.equals(username)) {
                String salt = getSalt();//生成新的盐值
                String pass = encrypt(username, newPassword, salt);//生成新的密钥
                //根据用户名把密钥和盐值都进行修改
                user.setPassword(pass);
                user.setSalt(salt);
                userService.updateUser(user);
            }

        } catch (RuntimeException e) {
            //打印异常信息
            System.out.println(e.getMessage());
            return new CommonResult(CommonParams.FAILURE, "原密码输入有误！");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new CommonResult(CommonParams.SUCCESS, "修改成功！");
    }

    //删除使用的接口
    @RequestMapping(value = "/deleteUserById/{id}", method = RequestMethod.POST)
    public CommonResult deleteUserById(@PathVariable("id") Integer id) {
        return new CommonResult<>(CommonParams.SUCCESS, "删除成功！", userService.deleteUser(id));
    }
}
